//
//  WBHomeCell.swift
//  SinaWeibo
//
//  Created by 风不会停息 on 2016/11/18.
//  Copyright © 2016年 风不会停息. All rights reserved.
//

import UIKit
import SDWebImage
private let margin: CGFloat = 8

//配图之间的距离
private let imageMargin: CGFloat = 2
private let maxWidth = ScreenWidth - 2 * margin
private let itemWidth = (maxWidth - 2 * imageMargin) / 3

class WBHomeCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var retweetLabel: YYLabel!
    @IBOutlet weak var imgVIcon: UIImageView!
    
    @IBOutlet weak var MbRankView: UIImageView!
    
    @IBOutlet weak var AvatarView: UIImageView!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var sourceLabel: UILabel!
    
    @IBOutlet weak var contentLabel: YYLabel!
    
    //微博配图的容器
    @IBOutlet weak var pictureView: WBPictureView!
    
    //配图容器根据数量来决定宽高的约束
    @IBOutlet weak var pictureHeightCon: NSLayoutConstraint!
    
    @IBOutlet weak var pictureWidthCon: NSLayoutConstraint!
    
    //设置itemsize等属性
    @IBOutlet weak var pictureViewFlowLayout: UICollectionViewFlowLayout!
    
    //配图视图顶部约束对象
    @IBOutlet weak var pictureViewTopCon: NSLayoutConstraint!
    
    @IBOutlet weak var toolBar: UIView!
    
    var viewmodel:WBStatusViewModel?{
        
            didSet{
            
            imgVIcon.sd_setImage(with: viewmodel?.iconURL)
            nameLabel.text = viewmodel?.status?.user?.name
//            timeLabel.text = viewmodel?.status?.created_at
            timeLabel.text = viewmodel?.timeText
            sourceLabel.text = viewmodel?.sourceText
            contentLabel.attributedText = viewmodel?.originalAttributedString
                if retweetLabel != nil {
                    retweetLabel.attributedText = viewmodel?.retweetedAttributedString
                }
            
            MbRankView.image = viewmodel?.mRankView
            AvatarView.image = viewmodel?.avatarView
            
                
            
            let count = viewmodel?.imageUrls?.count ?? 0
            //图片视图顶部的约束随着有无图片进行更新
            pictureViewTopCon.constant = count==0 ? 0:margin
            
            let result = calcultePictureViewSize(count: count)
            //根据约束对象的约束值
            pictureWidthCon.constant = result.pSize.width
            pictureHeightCon.constant = result.pSize.height
            pictureViewFlowLayout.itemSize = result.itemSize
            //配图视图的数据源
            pictureView.pictureInfos = viewmodel?.imageUrls
//                if viewmodel?.status?.retweeted_status != nil {
//                    //强制解包会崩溃，因为原创微博没有retweeted
//                    retweetLabel.text = viewmodel?.status?.retweeted_status?.text
//                }
                //也可以用隐式的可选解包
                
                
            //8.1之后，添加约束不会立即生效需要layoutsubview,cell复用的时候会出现一些问题
            pictureView.layoutIfNeeded()
//            retweetLabel?.attributedText = viewmodel?.retweetedAttributedString
                
                
                contentLabel.highlightTapAction = {(containerView, text, range, rect) -> () in
                    
                    //containerView被点击的视图
                    //text被点击的文本
                    //range点击特殊文本的范围
                    //rect点击特殊文本的坐标
                    
                    let sub = (text.string as NSString).substring(with: range)
                    
                    print(sub)
                    
                    if sub.hasPrefix("http"){
                        
                        //实例化控制器
                        let webVC = WBWebViewViewController()
                        //跳转控制器push
                        webVC.urlString = sub
                        
                        self.findNavController()?.pushViewController(webVC, animated: true)
                    }
                    
                }
                if (retweetLabel != nil) {
                    retweetLabel.highlightTapAction = {
                        (containerView, text, range, rect) -> () in
                        
                        //containerView被点击的视图
                        //text被点击的文本
                        //range点击特殊文本的范围
                        //rect点击特殊文本的坐标
                        
                        let sub = (text.string as NSString).substring(with: range)
                        
                        print(sub)
                        if sub.hasPrefix("http"){
                            
                            //实例化控制器
                            let webVC = WBWebViewViewController()
                            //跳转控制器push
                            webVC.urlString = sub
                            
                            self.findNavController()?.pushViewController(webVC, animated: true)
                        }
                        
                    }
                }
               
            
        }
        
        
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
//        self.backgroundColor = randomColor()
        self.contentLabel.numberOfLines = 0
        //要用可选解包，因为retweet可能为nil
        self.retweetLabel?.numberOfLines = 0
        //设置最大的布局宽度
        //print(self.bounds)
        self.contentLabel.preferredMaxLayoutWidth = ScreenWidth  - 2 *  margin
        self.retweetLabel?.preferredMaxLayoutWidth = ScreenWidth  - 2 *  margin
        
        self.contentLabel.font = UIFont.systemFont(ofSize: 15)
        
        //设置流水布局
        pictureViewFlowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //设置行列最小间距
        pictureViewFlowLayout.minimumLineSpacing = imageMargin
        pictureViewFlowLayout.minimumInteritemSpacing = imageMargin
        
  
    }

    
  //根据图片的张数计算配图的张数，更新配图视图的宽高约束的值
    private func calcultePictureViewSize(count: Int) -> (pSize: CGSize,itemSize: CGSize) {
        if count == 0 {
            return (CGSize(width: 1, height: 1),CGSize(width: 1, height: 1))
        }
        
        if count == 1 {
            //计算图片的大小  获取图片  -> image.size  必须确保在这里一定能够获取到图片
            //不能够在这个地方下载图片 否则会执行多次刷新(有多少个单张图片就需要刷新多少次)
            if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: viewmodel?.imageUrls?.last?.wap360 ?? "") {
                let imageSize = image.size
                //不能再if中单独设置itemSize
                //pictureViewFlowLayout.itemSize = imageSize
                return (imageSize,imageSize)
            }
            
            return (CGSize(width: itemWidth, height: itemWidth),CGSize(width: itemWidth, height: itemWidth))
        }
        
        //判断四张图片
        if count == 4 {
            let width = 2 * itemWidth + margin
            return (CGSize(width: width, height: width),CGSize(width: itemWidth, height: itemWidth))
        }
        
        //其他的多张图片 需要确定行数
        /*
         1,2,3  1
         4,5,6  2
         7,8,9  3
         */
        //一只列数和总个数 需要确定行数
        let row = CGFloat((count - 1) / 3) + 1
        let h = row * itemWidth + (row - 1) * imageMargin
        return (CGSize(width: maxWidth, height: h),CGSize(width: itemWidth, height: itemWidth))
    }
    
}
